import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';
import '../../../function/model/plant_record_model.dart';
import '../../../function/state/plant_record_state.dart';
import '../../../function/utils/image_manager.dart';

/// 植物成长记录页面控制器
/// 使用GetX进行页面逻辑分离
class GrowthTrackingController extends GetxController {
  // 植物记录状态管理
  final PlantRecordState plantRecordState = Get.find<PlantRecordState>();

  // 选中的日期
  final Rx<DateTime> selectedDate = DateTime.now().obs;

  // 选中的图片
  final RxList<File> selectedImages = <File>[].obs;

  // 表单控制器
  final TextEditingController plantHeightController = TextEditingController();
  final TextEditingController totalBladesController = TextEditingController();
  final TextEditingController healthyLeavesController = TextEditingController();
  final TextEditingController yellowedLeavesController =
      TextEditingController();
  final TextEditingController wateringVolumeController =
      TextEditingController();
  final TextEditingController applicationRateController =
      TextEditingController();
  final TextEditingController totalBloomsController = TextEditingController();
  final TextEditingController halfOpenFlowersController =
      TextEditingController();
  final TextEditingController wiltedFlowersController = TextEditingController();

  // 选中的选项
  final Rx<WateringMethod?> selectedWateringMethod = Rx<WateringMethod?>(null);
  final Rx<FertilizerType?> selectedFertilizerType = Rx<FertilizerType?>(null);
  final Rx<ApplicationMethod?> selectedApplicationMethod =
      Rx<ApplicationMethod?>(null);
  final Rx<PestDiseaseType?> selectedPestDiseaseType = Rx<PestDiseaseType?>(
    null,
  );
  final Rx<OnsetSite?> selectedOnsetSite = Rx<OnsetSite?>(null);

  // 下拉选项控制器
  final TextEditingController wateringMethodController =
      TextEditingController();
  final TextEditingController fertilizerTypeController =
      TextEditingController();
  final TextEditingController applicationMethodController =
      TextEditingController();
  final TextEditingController pestDiseaseTypeController =
      TextEditingController();
  final TextEditingController onsetSiteController = TextEditingController();

  // 选项列表
  List<String> get wateringMethodOptions =>
      WateringMethod.values.map((e) => e.displayName).toList();
  List<String> get fertilizerTypeOptions =>
      FertilizerType.values.map((e) => e.displayName).toList();
  List<String> get applicationMethodOptions =>
      ApplicationMethod.values.map((e) => e.displayName).toList();
  List<String> get pestDiseaseTypeOptions =>
      PestDiseaseType.values.map((e) => e.displayName).toList();
  List<String> get onsetSiteOptions =>
      OnsetSite.values.map((e) => e.displayName).toList();

  @override
  void onInit() {
    super.onInit();
    _loadCurrentRecord();
  }

  @override
  void onClose() {
    // 释放控制器资源
    plantHeightController.dispose();
    totalBladesController.dispose();
    healthyLeavesController.dispose();
    yellowedLeavesController.dispose();
    wateringVolumeController.dispose();
    applicationRateController.dispose();
    totalBloomsController.dispose();
    halfOpenFlowersController.dispose();
    wiltedFlowersController.dispose();
    wateringMethodController.dispose();
    fertilizerTypeController.dispose();
    applicationMethodController.dispose();
    pestDiseaseTypeController.dispose();
    onsetSiteController.dispose();
    super.onClose();
  }

  /// 加载当前记录
  void _loadCurrentRecord() {
    final record = plantRecordState.getRecordByDate(selectedDate.value);
    if (record != null) {
      _populateForm(record);
    } else {
      _clearForm();
    }
  }

  /// 填充表单
  void _populateForm(PlantRecordModel record) {
    plantHeightController.text = record.plantHeight?.toString() ?? '';
    totalBladesController.text = record.totalBlades?.toString() ?? '';
    healthyLeavesController.text = record.healthyLeaves?.toString() ?? '';
    yellowedLeavesController.text = record.yellowedLeaves?.toString() ?? '';
    wateringVolumeController.text =
        record.totalWateringVolume?.toString() ?? '';
    applicationRateController.text = record.applicationRate?.toString() ?? '';
    totalBloomsController.text = record.totalBlooms?.toString() ?? '';
    halfOpenFlowersController.text = record.halfOpenFlowers?.toString() ?? '';
    wiltedFlowersController.text = record.wiltedFlowers?.toString() ?? '';

    selectedWateringMethod.value = record.wateringMethod;
    selectedFertilizerType.value = record.fertilizerType;
    selectedApplicationMethod.value = record.applicationMethod;
    selectedPestDiseaseType.value = record.pestDiseaseType;
    selectedOnsetSite.value = record.onsetSite;

    // 更新下拉选项控制器
    wateringMethodController.text = record.wateringMethod?.displayName ?? '';
    fertilizerTypeController.text = record.fertilizerType?.displayName ?? '';
    applicationMethodController.text =
        record.applicationMethod?.displayName ?? '';
    pestDiseaseTypeController.text = record.pestDiseaseType?.displayName ?? '';
    onsetSiteController.text = record.onsetSite?.displayName ?? '';

    // 加载图片从本地路径
    selectedImages.clear();
    for (final imagePath in record.plantImages) {
      final file = ImageManager.getImageFile(imagePath);
      if (file != null) {
        selectedImages.add(file);
      }
    }
  }

  /// 清空表单
  void _clearForm() {
    plantHeightController.clear();
    totalBladesController.clear();
    healthyLeavesController.clear();
    yellowedLeavesController.clear();
    wateringVolumeController.clear();
    applicationRateController.clear();
    totalBloomsController.clear();
    halfOpenFlowersController.clear();
    wiltedFlowersController.clear();

    selectedWateringMethod.value = null;
    selectedFertilizerType.value = null;
    selectedApplicationMethod.value = null;
    selectedPestDiseaseType.value = null;
    selectedOnsetSite.value = null;

    // 清空下拉选项控制器
    wateringMethodController.clear();
    fertilizerTypeController.clear();
    applicationMethodController.clear();
    pestDiseaseTypeController.clear();
    onsetSiteController.clear();

    selectedImages.clear();
  }

  /// 选择日期
  void selectDate(DateTime date) {
    selectedDate.value = date;
    _loadCurrentRecord();
  }

  /// 检查是否可以编辑当前选中的日期
  bool canEditSelectedDate() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final targetDay = DateTime(
      selectedDate.value.year,
      selectedDate.value.month,
      selectedDate.value.day,
    );

    final canEdit = targetDay.isAtSameMomentAs(today);
    print(
      'canEditSelectedDate: $canEdit, today: $today, targetDay: $targetDay',
    );
    // 只有今天可以编辑
    return canEdit;
  }

  /// 获取当前月份和年份
  String getCurrentMonthYear() {
    final now = DateTime.now();
    final months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ];
    return '${months[now.month - 1]} ${now.year}';
  }

  /// 获取本周的日期
  List<DateTime> getCurrentWeekDays() {
    final now = DateTime.now();
    // 从周一开始显示，weekday 1=Monday, 7=Sunday
    final startOfWeek = now.subtract(Duration(days: now.weekday - 1));

    return List.generate(7, (index) {
      return startOfWeek.add(Duration(days: index));
    });
  }

  /// 检查指定日期是否有记录
  bool hasRecordForDate(DateTime date) {
    return plantRecordState.getRecordByDate(date) != null;
  }

  /// 选择图片
  Future<void> pickImages(BuildContext context) async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1, // 只能选择一张图片
          selectedAssets: [],
          requestType: RequestType.image,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final asset = assets.first;
        final file = await asset.file;
        if (file != null) {
          selectedImages.clear(); // 清空之前的图片
          selectedImages.add(file); // 添加新选择的图片
        }
      }
    } catch (e) {
      Get.snackbar(
        'Error',
        'Failed to pick image: $e',
        snackPosition: SnackPosition.TOP,
      );
    }
  }

  /// 移除图片
  void removeImage(int index) {
    if (index >= 0 && index < selectedImages.length) {
      selectedImages.removeAt(index);
    }
  }

  /// 处理浇水方式选择
  void onWateringMethodSelected(String value) {
    wateringMethodController.text = value;
    selectedWateringMethod.value = WateringMethod.values.firstWhere(
      (e) => e.displayName == value,
    );
  }

  /// 处理肥料类型选择
  void onFertilizerTypeSelected(String value) {
    fertilizerTypeController.text = value;
    selectedFertilizerType.value = FertilizerType.values.firstWhere(
      (e) => e.displayName == value,
    );
  }

  /// 处理施肥方式选择
  void onApplicationMethodSelected(String value) {
    applicationMethodController.text = value;
    selectedApplicationMethod.value = ApplicationMethod.values.firstWhere(
      (e) => e.displayName == value,
    );
  }

  /// 处理病虫害类型选择
  void onPestDiseaseTypeSelected(String value) {
    pestDiseaseTypeController.text = value;
    selectedPestDiseaseType.value = PestDiseaseType.values.firstWhere(
      (e) => e.displayName == value,
    );
  }

  /// 处理发病部位选择
  void onOnsetSiteSelected(String value) {
    onsetSiteController.text = value;
    selectedOnsetSite.value = OnsetSite.values.firstWhere(
      (e) => e.displayName == value,
    );
  }

  /// 清空表单
  void clearForm() {
    _clearForm();
  }

  /// 保存记录
  Future<void> saveRecord(BuildContext context) async {
    try {
      // 检查是否可以编辑当前选中的日期
      if (!canEditSelectedDate()) {
        Get.snackbar(
          'Error',
          'Can only edit today\'s record',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red,
          colorText: Colors.white,
        );
        return;
      }

      // 复制图片到本地目录
      List<String> localImagePaths = [];
      for (final file in selectedImages) {
        final localPath = await ImageManager.copyImageToLocal(file);
        if (localPath != null) {
          localImagePaths.add(localPath);
        }
      }

      // 创建植物记录
      final record = PlantRecordModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        recordDate: selectedDate.value,
        plantImages: localImagePaths,
        plantHeight: double.tryParse(plantHeightController.text),
        totalBlades: int.tryParse(totalBladesController.text),
        healthyLeaves: int.tryParse(healthyLeavesController.text),
        yellowedLeaves: int.tryParse(yellowedLeavesController.text),
        totalWateringVolume: double.tryParse(wateringVolumeController.text),
        wateringMethod: selectedWateringMethod.value,
        applicationRate: double.tryParse(applicationRateController.text),
        fertilizerType: selectedFertilizerType.value,
        applicationMethod: selectedApplicationMethod.value,
        totalBlooms: int.tryParse(totalBloomsController.text),
        halfOpenFlowers: int.tryParse(halfOpenFlowersController.text),
        wiltedFlowers: int.tryParse(wiltedFlowersController.text),
        pestDiseaseType: selectedPestDiseaseType.value,
        onsetSite: selectedOnsetSite.value,
      );

      // 保存到状态管理
      plantRecordState.addRecord(record);

      // 显示成功消息
      Get.snackbar(
        'Success',
        'Record saved successfully',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );

      // 重新加载当前记录以显示保存的内容
      _loadCurrentRecord();
    } catch (e) {
      Get.snackbar(
        'Error',
        'Failed to save record: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }
}
